package neu.edu.cn.nuemall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import neu.edu.cn.nuemall.dto.OrderInfoDTO;
import neu.edu.cn.nuemall.dto.OrderItemDTO;
import neu.edu.cn.nuemall.entity.BooksSku;

import neu.edu.cn.nuemall.entity.CartItem;
import neu.edu.cn.nuemall.entity.OrderInfo;
import neu.edu.cn.nuemall.entity.OrderItem;
import neu.edu.cn.nuemall.mapper.*;
import neu.edu.cn.nuemall.service.BooksService;
import neu.edu.cn.nuemall.service.OrderService;
import neu.edu.cn.nuemall.service.PublishService;
import neu.edu.cn.nuemall.service.UserinfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
   @Autowired
   private UserinfoService userinfoService;
   @Autowired
   private OrderInfoMapper orderInfoMapper;
   @Autowired
   BooksSkuMapper booksSkuMapper;
   @Autowired
   private OrderItemMapper orderItemMapper;
   @Autowired
   private BooksService booksService;
   @Autowired
   private PublishService publishService;
   @Autowired
   private CartItemMapper cartItemMapper;
    @Override
    public OrderInfo submitOrder(String skuId, Integer booksCount, Double totalPrice, String shippingAddress
            , String fromType, String[] cartItems) {

        OrderInfo order = new OrderInfo();
        order.setId(UUID.randomUUID().toString());
        order.setCreateAt(new Date());
        order.setUserId(userinfoService.getCurrentUser());
        order.setShippingAddress(shippingAddress);
        // 默认为待支付状态
        order.setState(0);
        order.setTotalCount(booksCount);
        order.setTotalPrice(new BigDecimal(totalPrice));
        orderInfoMapper.insert(order);

        if (fromType.equals("buy")) {
            // 插入OrderItem
            OrderItem orderItem = new OrderItem();
            orderItem.setId(UUID.randomUUID().toString());
            orderItem.setOrderId(order.getId());
            orderItem.setCount(1);
            orderItem.setSkuId(skuId);
            BooksSku booksSku = booksSkuMapper.selectById(skuId);
            orderItemMapper.insert(orderItem);
        }
        else if(fromType.equals("cart"))
        {
            for (String cartItemId : cartItems) {
                CartItem cartItem = cartItemMapper.selectById(cartItemId);
                if (cartItem != null) {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setId(UUID.randomUUID().toString());
                    orderItem.setOrderId(order.getId());
                    orderItem.setCount(cartItem.getCount());
                    orderItem.setSkuId(cartItem.getSkuId());
                    orderItemMapper.insert(orderItem);
                    order.setTotalCount(booksCount);
                    order.setTotalPrice(new BigDecimal(totalPrice));
                }
                cartItemMapper.deleteById(cartItemId);
            }
        }
        return order;
    }
    @Override
    public int payOrder(String orderId) {

        OrderInfo orderInfo=orderInfoMapper.selectById(orderId);
        orderInfo.setState(20);
        int i=orderInfoMapper.updateById(orderInfo);
        return i;

    }

    @Override
    public OrderInfoDTO getOrder(String orderId) {
        OrderInfo orderInfo=orderInfoMapper.selectById(orderId);
        OrderInfoDTO orderDTO=new OrderInfoDTO();
        BeanUtils.copyProperties(orderInfo,orderDTO);
        //查询订单购买条目列表
        QueryWrapper<OrderItem> queryWrapper=new QueryWrapper<OrderItem>();
        queryWrapper.eq("order_id",orderId);
        List<OrderItem> orderItems=orderItemMapper.selectList(queryWrapper);
        //把查询出的OrderItem列表映射成为OrderItemDTO的列表
        List<OrderItemDTO> orderItemDtos = orderItems.stream().map(orderItem -> {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            orderItemDTO.setId(orderItem.getId());
            orderItemDTO.setCount(orderItem.getCount());
            orderItemDTO.setBooksSkuDTO(booksService.getBookSkuById(orderItem.getSkuId()));
            orderItemDTO.setBooks(booksService.getBooksById(orderItemDTO.getBooksSkuDTO().getBooksId()));
            orderItemDTO.setPublish(publishService.getPublishById(orderItemDTO.getBooks().getBelongPublishId()));
            return orderItemDTO;
        }).collect(Collectors.toList());

        orderDTO.setOrderItemDTOList(orderItemDtos);
        return orderDTO;
    }

    @Override
    public PageInfo<OrderInfoDTO> getOrderList(Integer page) {

        Page<OrderInfo> orderPage = PageHelper.startPage(page, 4);

        QueryWrapper<OrderInfo> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("user_id", userinfoService.getCurrentUser());
        orderQueryWrapper.orderByDesc("create_at");
        List<OrderInfo> orderList = orderInfoMapper.selectList(orderQueryWrapper);

        PageInfo<OrderInfoDTO> pageInfo = orderPage.toPageInfo(order -> {
            OrderInfoDTO orderDTO = new OrderInfoDTO();
            BeanUtils.copyProperties(order, orderDTO);
            // 查询订单购买条目列表
            QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
            orderItemQueryWrapper.eq("order_id", order.getId());

            List<OrderItemDTO> orderItemDTOs = orderItemMapper.selectList(orderItemQueryWrapper).stream().map(orderItem -> {
                OrderItemDTO orderItemDTO = new OrderItemDTO();
                orderItemDTO.setId(orderItem.getId());
                orderItemDTO.setCount(orderItem.getCount());
                orderItemDTO.setBooksSkuDTO(booksService.getBookSkuById(orderItem.getSkuId()));
                orderItemDTO.setBooks(booksService.getBooksBaseInfoById(orderItemDTO.getBooksSkuDTO().getBooksId()));

                return orderItemDTO;
            }).collect(Collectors.toList());

            orderDTO.setOrderItemDTOList(orderItemDTOs);
            return orderDTO;
        });
        return pageInfo;
    }

}
